const api = 'http://api.zymk.cn/app_api/v3/'
const mkxq = 'http://mkxq.zymk.cn/user/v1/'
const userInfo = getCookie('user')

var vcPending = false;
var vcTimer = null;
var sec = 60;

var loginMode = true;	// true Vc登录, false Pw登录
var pwShow = false;	// true 显示, false 隐藏

var layer = {
	msg: function(text) {
		var _this = this;
		_this.reset();
		var html;
		$('.layer').css('display', 'flex');
		html = "<img src='../../../static/images/change.png'><span class='msg_text'>" + text + "</span>"
		$('.layerMsg').html(html);

		setTimeout(_this.reset, 1500);
	},
	reset: function() {
		$('.layer').hide().off('click').attr('class', 'layer');
		$('.layerMsg').html('');
	}
}

function goback() {
	history.go(-1)
}

function pwShowSwitch() {
	pwShow = !pwShow
	if(pwShow){
		$('.pwShowSwitch').removeClass('ift-yanjing_close').addClass('ift-yanjing')
		$('#pw_show').show()
		$('#pw_hide').hide()
	}else{
		$('.pwShowSwitch').removeClass('ift-yanjing').addClass('ift-yanjing_close')
		$('#pw_show').hide()
		$('#pw_hide').show()
	}
}

function forgot() {
	this.$router.push('/forgotPw')
}

function modeSwitch() {
	loginMode = !loginMode;
	if(loginMode){
		$('.login_bananer').eq(0).show()
		$('.login_bananer').eq(1).hide()
		$('#mobile').show()
		$('#identity').hide()
		$('.vc-input').show()
		$('.password').hide()
		$('.forgot').hide()
		$('.switchLogin span').eq(0).show()
		$('.switchLogin span').eq(1).hide()
	}else{
		$('.login_bananer').eq(0).hide()
		$('.login_bananer').eq(1).show()
		$('#mobile').hide()
		$('#identity').show()
		$('.vc-input').hide()
		$('.password').show()
		$('.forgot').show()
		$('.switchLogin span').eq(0).hide()
		$('.switchLogin span').eq(1).show()
	}
}

function getVc() {
	var mobile = $('#mobile').val();
	console.log(mobile);
	if (vcPending) {
		// 若已请求过验证码，则不响应点击事件
		layer.msg('验证码正在路上，请耐心等待哦')
		return false;
	} else {
		if (mobileReg(mobile)) {
			$.ajax({
				url: mkxq + 'mobilevc/',
				type: 'POST',
				dataType: 'jsonp',
				data: { mobile, service: 'mkn' },
				success: function (res) {
					var resData = JSON.parse(res);
					if (resData.status == 0) {
						layer.msg('发送成功，请等待接收')

						clearInterval(vcTimer);
						vcPending = true;
						vcTimer = setInterval(() => {
							if (sec > 0) {
								sec--;
								$('.getVc').text(sec + '秒');
							} else {
								// 重置样式和状态
								clearInterval(vcTimer);
								vcPending = false;
								sec = 60;
								$('.getVc').text('点击发送');
							}
						}, 1000);
					} else {
						layer.msg(resData.msg)
					}
				}
			})
		} else {
			layer.msg('请输入正确的手机号码')
		}
	}
}

function getLocation(cb) {
	$.ajax({
		// url: 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json',
		url: '/ip/iplookup/iplookup.php?format=json',
		success: function (ip_res) {
			console.log(ip_res);
			if (ip_res.status == 200) {
				let locObj = {};
				locObj['country'] = ip_res.data.country;
				locObj['province'] = ip_res.data.province;
				locObj['city'] = ip_res.data.city;								
				// cookie
				setCookie('location', JSON.stringify(locObj));
			}
		}
	})
	.done(function () {
		typeof cb === 'function' && cb()
	})
}

function getUserInfo(type, token, cb, client) {
	client = client ? client : ''
	$.ajax({
		url: api + 'getuserinfo/',
		dataType: 'jsonp',
		data: { type, token, client }
	})
	.done(function (user_res) {
		typeof cb === 'function' && cb(user_res)
	})
	.fail(function (e) {
		layer.msg(e)
	})
}

function login() {
	var mobile = $('#mobile').val();
	var vCode = $('#vCode').val();
	var identity = $('#identity').val();
	var pwd = $('#pw_show').val();

	if (loginMode) {
		// Vc登陆
		if (mobileReg(mobile) && vCode.length > 0) {
			// 验证码验证
			$.ajax({
				url: mkxq + 'mobilebind/',
				dataType: 'jsonp',
				data: { mobile, vCode, service: 'mkn' },
				success: function (vc_res) {
					vc_res = JSON.parse(vc_res);
					if (vc_res.status === 0) {
						let needPwd = false;
						if (vc_res.data.user.needPwd) {
							needPwd = true;
						}
						let type = 'mkxq';
						let token = vc_res.data.appToken;
						// 请求用户信息
						getUserInfo(type, token, function (user_res) {							
							if (user_res.status == 0) {
								setCookie('user', JSON.stringify(user_res.data));
								// getLocation(cb)
								if (needPwd) {
									location.replace('/setpw?token=' + UrlEncode(vc_res.data.token));
								} else {
									let redirect_uri = getCookie('login_from', true);
									setCookie('login_from', null, -1);
									location.replace(redirect_uri);
								}
							}else{
								layer.msg(user_res.msg)
							}
						})
					} else {
						layer.msg(vc_res.msg)
					}
				}
			})
		} else {
			layer.msg('请检查您的输入~')
		}
	} else {
		// pw登陆
		if (identity.length > 0 && pwdReg(pwd)) {
			$.ajax({
				url: mkxq + 'login/',
				dataType: 'jsonp',
				data: { identity, pwd },
				success: function (res) {
					res = JSON.parse(res)
					if (res.status == 0) {
						let type = 'mkxq';
						let token = res.data.appToken;
						// 请求用户信息
						getUserInfo(type, token, function (user_res) {
							if (user_res.status == 0) {
								setCookie('user', JSON.stringify(user_res.data));
								// getLocation(cb)
								let redirect_uri = getCookie('login_from', true);
								setCookie('login_from', null, -1);
								location.replace(redirect_uri);
							}else{
								layer.msg(user_res.msg)
							}
						})
					} else {
						layer.msg(res.msg)
					}
				}
			})
		} else {
			layer.msg('请检查您的输入~')
		}
	}
}

function thirdTapHandle(e) {
	let host = location.origin;
	// let redirect_uri = location.href;
	// console.log(redirect_uri);
	// setCookie('third_from', redirect_uri);
	let flag = e.target.dataset.flag;
	let url = '';
	switch (flag) {
		case 'qq':
			url = 'https://graph.qq.com/oauth2.0/authorize?client_id=101369285&response_type=token&scope=get_user_info&redirect_uri=' + encodeURIComponent(host + '/login' + '?type=qq')
			break;
		case 'sina':
			url = 'https://api.weibo.com/oauth2/authorize?client_id=199818462&redirect_uri=' + encodeURIComponent(host + '/login' + '?type=sina')
			break;
		case 'weixin':
			if (host.substr(0, 9) == 'http://m.') {
				host = host.replace('http://m.', 'http://www.');
				console.log(host);
			}
			url = 'https://open.weixin.qq.com/connect/qrconnect?appid=wx49c269dceb6ed1e3&redirect_uri=' + encodeURIComponent(host + '/login') + '&response_type=code&scope=snsapi_login&state=weixin#wechat_redirect'
			break;
	}
	location.href = url;
}

function thirdCallback() {
	var search = location.search;
	var matchType = search.match(/(type|state)\=([a-z0-9]+)/i);
	var type = matchType ? matchType[2].toLocaleLowerCase() : false;
	var token = '', lastargs = '';

	if (!type) {
		layer.msg('未获取到登录方式，请重新刷新再试!')
		return;
	}

	switch (type) {
		case 'qq':
			token = getCookie('access_token', true);
			setCookie('access_token', null, -1);
			break;
		case 'sina':
			var sinaMath = search.match(/code=([a-z0-9]+)/i);
			token = sinaMath ? sinaMath[1] : false;
			break;
		case 'weixin':
			var wixinMath = search.match(/code=([a-z0-9]+)/i);
			token = wixinMath ? wixinMath[1] : false;
			break;
	}

	if (!token) {
		layer.msg('登录授权失败，请重新刷新再试!')
		return;
	}

	let client = 'web';
	getUserInfo(type, token, function (user_res) {
		if (user_res.status == 0) {
			layer.msg('登陆成功，正在为您保存状态...')
			setTimeout(() => {
				setCookie('user', JSON.stringify(user_res.data), 365);
				var login_from = getCookie('login_from', true) || '/';
				if (login_from) {
					setCookie('login_from', null, -1);
					location.href = login_from;
				}
			}, 1000);
		} else {
			return false;
		}
	}, client)
}

$(function () {
	$('.getVc').on('click', getVc)
	$('.loginBtn').on('click', login)
	$('.switchLogin').on('click', modeSwitch)
	$('#pw_hide').on('keyup', function () {
		$('#pw_show').val($(this).val())
	})
	$('#pw_show').on('keyup', function () {
		$('#pw_hide').val($(this).val())
	})
	$('.pwShowSwitch').on('click', pwShowSwitch)
	$('.loginIcons').on('click', 'div', thirdTapHandle)

	if (location.search.match(/(type|state)\=([a-z0-9]+)/i)) {
		let hash = location.hash;
		if (hash.length > 0) {
			let access_token = hash.split('#access_token=')[1].split('&')[0];
			setCookie('access_token', access_token);
		}

		thirdCallback();
	}
})